<template>
  <view class="container">
    <!-- 顶部机构选择和评分 -->
    <view class="header">
      <view class="org-select" @click="showOrgPicker">
        <text class="org-name">{{ currentOrg }}</text>
        <uni-icons type="bottom" size="14" color="#666"></uni-icons>
      </view>
      <view class="score">
        <uni-icons type="star" size="16" color="#FFB800"></uni-icons>
        <text class="score-text">{{ score }}</text>
      </view>
    </view>

    <!-- 状态切换标签 -->
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: currentTab === index }"
        @click="() => switchTab(index)"
      >
        {{ tab }}
      </view>
      <view class="tab-line" :style="{ left: tabLineLeft }"></view>
    </view>

    <!-- 课程列表 -->
    <view 
      class="course-item" 
      v-for="(course, index) in courses" 
      :key="course.id"
      @click="() => enterCourses(course)"
    >
      <!-- 使用 course.id 作为 key -->
      <image class="course-image" :src="course.image" mode="aspectFill"></image>
      <view class="course-info">
        <text class="course-name">{{ course.className }}</text>
        <view class="course-detail">
          <view class="teacher">
            <uni-icons type="person" size="14" color="#666"></uni-icons>
            <text>{{ course.username }}</text>
          </view>
          <view class="time">
            <uni-icons type="calendar" size="14" color="#666"></uni-icons>
            <text>{{ course.beginDate }}至{{ course.endDate }}</text>
          </view>
        </view>
      </view>
    </view>
    

    <!-- 机构选择弹出层 -->
    <uni-popup ref="orgPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text>选择机构</text>
          <uni-icons type="closeempty" size="20" @click="closeOrgPicker"></uni-icons>
        </view>
        <view class="org-list">
          <view 
            class="org-item" 
            v-for="(org, index) in orgs" 
            :key="index"
            :class="{ 'org-active': org === currentOrg }"
            @click="() => selectOrg(org)"
          >
            {{ org }}
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

// 定义响应式数据
const currentOrg = ref('中软国际教育科技');
const score = ref('2.6');
const tabs = ['进行中', '已结束', '即将开始'];
const currentTab = ref(0);
const orgs = ['中软国际教育科技', '清华大学', '北京大学', '浙江大学'];
const courses = ref([]); // 初始化为空数组，用于存储从API获取的课程数据

// 计算属性
const tabLineLeft = computed(() => `${(currentTab.value * 33.33)}%`);
const filteredCourses = computed(() => {
  if (currentTab.value === 0) {
    return courses.value.filter(course => course.status === '进行中');
  } else if (currentTab.value === 1) {
    return courses.value.filter(course => course.status === '已结束');
  } else if (currentTab.value === 2) {
    return courses.value.filter(course => course.status === '即将开始');
  }
  return courses.value;
});

// 方法
const showOrgPicker = () => orgPopup.value.open();
const closeOrgPicker = () => orgPopup.value.close();
const selectOrg = (org) => {
  currentOrg.value = org;
  closeOrgPicker();
  fetchCourseData(); // 切换机构后刷新数据
};
const switchTab = (index) => {
  currentTab.value = index;
  fetchCourseData(); // 切换标签时刷新数据
};
const enterCourse = (course) => {
  console.log(11111);
  uni.reLaunch({
    url: "/pages/study/course-detail",
  });
};

// 获取课程数据
const fetchCourseData = () => {
  return new Promise((resolve, reject) => {
    let apiPath = '';
    const params = { id: '1' };

    // 根据 currentTab 选择不同的 API 路径
    if (currentTab.value === 0) {
      apiPath = 'http://192.168.100.54:8080/classes/findclassesstar';
    } else if (currentTab.value === 1) {
      apiPath = 'http://192.168.100.54:8080/classes/findclassesend';
    } else if (currentTab.value === 2) {
      apiPath = 'http://192.168.100.54:8080/classes/findclassescoming';
    }

    uni.request({
      url: apiPath, // 请求的URL
      method: 'GET', // 请求方法
      data: params, // 请求参数
      success: (res) => {
        // 打印具体的响应数据（即 `res.data`）
        console.log('Courses data:', res.data);

        // 将获取到的课程数据赋值给 courses
        courses.value = res.data;

        resolve(res.data); // 解析为成功的Promise
      },
      fail: (err) => {
        console.error('Error fetching courses:', err);
        uni.showToast({
          title: '获取课程数据失败',
          icon: 'none'
        });
        reject(err); // 解析为失败的Promise
      }
    });
  });
};

// 单一的 enterCourse 函数声明
const enterCourses = (course) => {
  console.log('Entering course:', course); // 打印日志以确认点击事件被触发
  console.log(course.id) ;
  // 使用 uni.reLaunch 跳转到 course-detail 页面，并传递课程 ID 作为查询参数
  uni.reLaunch({
    url: `/pages/study/course-detail?id=${course.id}`, // 假设课程对象中有 id 字段
  });
};

// 生命周期钩子
onMounted(() => {
  fetchCourseData();
});

// 模板引用
const orgPopup = ref(null);
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  padding: 20rpx 30rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.org-select {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
  
  .org-name {
    font-size: 32rpx;
    font-weight: 500;
    margin-right: 10rpx;
  }
}

.score {
  display: flex;
  align-items: center;
  
  .score-text {
    font-size: 28rpx;
    color: #666;
    margin-left: 6rpx;
  }
}

.tabs {
  display: flex;
  position: relative;
  background-color: #fff;
  padding: 20rpx 0;
  
  .tab-item {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    position: relative;
    
    &.active {
      color: #2979ff;
      font-weight: 500;
    }
  }
  
  .tab-line {
    position: absolute;
    bottom: 0;
    width: 33.33%;
    height: 4rpx;
    background-color: #2979ff;
    transition: all 0.3s;
  }
}

.course-list {
  padding: 20rpx;
}

.course-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  display: flex;
  padding: 20rpx;
  
  .course-image {
    width: 200rpx;
    height: 140rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
  }
  
  .course-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .course-name {
      font-size: 30rpx;
      font-weight: 500;
    }
    
    .course-detail {
      font-size: 24rpx;
      color: #666;
      
      .teacher, .time {
        display: flex;
        align-items: center;
        margin-top: 10rpx;
        
        text {
          margin-left: 6rpx;
        }
      }
    }
  }
}

.popup-content {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
  
  .popup-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #eee;
    
    text {
      font-size: 32rpx;
      font-weight: 500;
    }
  }
  
  .org-list {
    padding: 20rpx 30rpx;
    
    .org-item {
      padding: 24rpx 0;
      font-size: 28rpx;
      border-bottom: 1rpx solid #eee;
      
      &.org-active {
        color: #2979ff;
      }
      
      &:last-child {
        border-bottom: none;
      }
    }
  }
}
</style> 